package cn.tedu.study.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author:yuziji
 * @create: 2023-06-08 11:28
 * @description:
 */
@Configuration
//开启方法授权的检测
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        当访问需要登录认证才能访问的资源时，没有登录的时候跳转到登录页面
        http.formLogin().loginPage("/usermodel/login.html");
//        设置黑名单，即需要登录才能访问的资源
        String[] urls = {"/usermodel/index.html", "/usermodel/personal.html", "/usermodel/friendlist.html"};
        http.authorizeHttpRequests()//对请求进行授权
                .mvcMatchers(urls)//匹配某些路径
                .authenticated()//需要通过登录认证放行
                .anyRequest()//其他任意请求
                .permitAll();//不需要登录也可以访问
//        关闭跨域攻击防御策略，否则所有post请求将失效
        http.csrf().disable();
    }

    //    配置密码加密的方式
    @Bean
    public PasswordEncoder passwordEncoder() {
//        返回此加密的编码器后，用户输入的密码会通过此编码器加密之后再和数据里面的密码进行比较
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}
